package cn.cosmosx.base.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import cn.cosmosx.base.define.BaseEntity;
import cn.cosmosx.base.define.BaseLogicEntity;
import cn.cosmosx.base.helper.SessionHelper;
import cn.cosmosx.base.util.ClassUtils;

import java.time.LocalDateTime;

/**
 * 自动填充功能处理器
 * 原理:
 * <p>
 * 实现元对象处理器接口：{@linkplain MetaObjectHandler}
 * <p>
 * 注解填充字段 @TableField(.. fill = FieldFill.INSERT) 生成器策略部分也可以配置
 */
@Slf4j
@Component
public class CustomMybatisPlusMetaObjectHandler implements MetaObjectHandler {
    // 创建人实体属性名
    private final static String creatorField = ClassUtils.toFieldName(BaseEntity::getCreator);
    // 创建时间实体属性名
    private final static String createTimeField = ClassUtils.toFieldName(BaseEntity::getCreateTime);
    // 更新人实体属性名
    private final static String updaterField = ClassUtils.toFieldName(BaseEntity::getUpdater);
    // 更新时间实体属性名
    private final static String updateTimeField = ClassUtils.toFieldName(BaseEntity::getUpdateTime);
    // 逻辑删除实体属性名
    private final static String deletedField = ClassUtils.toFieldName(BaseLogicEntity::getDeleted);
    // 版本号实体属性名
    private final static String versionField = ClassUtils.toFieldName(BaseLogicEntity::getVersion);

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject - 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setCreatedInfo(metaObject);
        this.setUpdatedInfo(metaObject);
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject - 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setUpdatedInfo(metaObject);
    }

    private void setCreatedInfo(MetaObject metaObject) {
        Object entity = metaObject.getOriginalObject();
        if (entity instanceof BaseLogicEntity) {
            this.setFieldValByName(deletedField, 0, metaObject);
            this.setFieldValByName(versionField, 0, metaObject);
        }
        if (entity instanceof BaseEntity) {
            try {
                this.setFieldValByName(creatorField, SessionHelper.getUserId(), metaObject);
            } catch (Exception e) {
                log.error("用户未登录，未获取到当前用户ID，[{}]设置失败:{}", creatorField, e.getMessage());
            }
            this.setFieldValByName(createTimeField, LocalDateTime.now(), metaObject);
        }
    }

    private void setUpdatedInfo(MetaObject metaObject) {
        Object entity = metaObject.getOriginalObject();
        if (entity instanceof BaseEntity) {
            try {
                this.setFieldValByName(updaterField, SessionHelper.getUserId(), metaObject);
            } catch (Exception e) {
                log.error("用户未登录，未获取到当前用户ID，[{}]设置失败:{}", updaterField, e.getMessage());
            }
            this.setFieldValByName(updateTimeField, LocalDateTime.now(), metaObject);
        }
    }

    @Override
    public boolean openInsertFill() {
        return true;
    }

    @Override
    public boolean openUpdateFill() {
        return true;
    }
}
